"""
Pacman包管理器实现
支持Arch Linux和Manjaro系统
"""

import subprocess
import shlex
from ..core import OnlinePackageManager


class PacmanManager(OnlinePackageManager):
    """Pacman包管理器"""
    
    def __init__(self, sudo=False):
        super(PacmanManager, self).__init__(sudo)
        self.name = "pacman"
        self.description = "Arch Linux包管理器"
        
    def is_available(self) -> bool:
        """检查pacman是否可用"""
        try:
            result = subprocess.run(
                ["pacman", "--version"],
                capture_output=True,
                text=True,
                check=False
            )
            return result.returncode == 0
        except (subprocess.SubprocessError, FileNotFoundError):
            return False
    
    def update(self):
        """更新包数据库"""
        cmd = ["pacman", "-Sy"]
        if self.sudo:
            cmd = ["sudo"] + cmd
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            return result.returncode == 0
        except subprocess.SubprocessError:
            return False
    
    def upgrade(self):
        """升级所有包"""
        cmd = ["pacman", "-Syu", "--noconfirm"]
        if self.sudo:
            cmd = ["sudo"] + cmd
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            return result.returncode == 0
        except subprocess.SubprocessError:
            return False
    
    def install(self, packages):
        """安装包"""
        if not packages:
            return False
            
        cmd = ["pacman", "-S", "--noconfirm"] + packages
        if self.sudo:
            cmd = ["sudo"] + cmd
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            return result.returncode == 0
        except subprocess.SubprocessError:
            return False
    
    def remove(self, packages):
        """移除包"""
        if not packages:
            return False
            
        cmd = ["pacman", "-Rs", "--noconfirm"] + packages
        if self.sudo:
            cmd = ["sudo"] + cmd
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            return result.returncode == 0
        except subprocess.SubprocessError:
            return False
    
    def search(self, pattern):
        """搜索包"""
        cmd = ["pacman", "-Ss", pattern]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            if result.returncode != 0:
                return []
            
            packages = []
            lines = result.stdout.strip().split('\n')
            
            for i in range(0, len(lines), 2):
                if i + 1 < len(lines):
                    name_line = lines[i].strip()
                    desc_line = lines[i + 1].strip()
                    
                    # 解析包名和版本
                    if '/' in name_line:
                        repo_name = name_line.split('/')[1]
                        if ' ' in repo_name:
                            name = repo_name.split(' ')[0]
                            version = repo_name.split(' ')[1] if len(repo_name.split(' ')) > 1 else ""
                        else:
                            name = repo_name
                            version = ""
                    else:
                        name = name_line
                        version = ""
                    
                    packages.append({
                        'name': name,
                        'version': version,
                        'description': desc_line,
                        'repository': 'pacman'
                    })
            
            return packages
        except subprocess.SubprocessError:
            return []
    
    def info(self, package):
        """获取包信息"""
        cmd = ["pacman", "-Si", package]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            if result.returncode != 0:
                return None
            
            info = {}
            for line in result.stdout.strip().split('\n'):
                if ':' in line:
                    key, value = line.split(':', 1)
                    key = key.strip().lower().replace(' ', '_')
                    value = value.strip()
                    info[key] = value
            
            return {
                'name': package,
                'version': info.get('version', ''),
                'description': info.get('description', ''),
                'size': info.get('installed_size', ''),
                'repository': info.get('repository', '')
            }
        except subprocess.SubprocessError:
            return None
    
    def list_installed(self):
        """列出已安装的包"""
        cmd = ["pacman", "-Q"]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            if result.returncode != 0:
                return []
            
            packages = []
            for line in result.stdout.strip().split('\n'):
                if line:
                    parts = line.split()
                    if len(parts) >= 2:
                        packages.append({
                            'name': parts[0],
                            'version': parts[1],
                            'architecture': parts[2] if len(parts) > 2 else ''
                        })
            
            return packages
        except subprocess.SubprocessError:
            return []
    
    def installed(self, package):
        """检查包是否已安装"""
        cmd = ["pacman", "-Q", package]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            return result.returncode == 0
        except subprocess.SubprocessError:
            return False
    
    def clean_cache(self):
        """清理包缓存"""
        cmd = ["pacman", "-Scc", "--noconfirm"]
        if self.sudo:
            cmd = ["sudo"] + cmd
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, check=False)
            return result.returncode == 0
        except subprocess.SubprocessError:
            return False